<template>
  <a-modal
    v-model:open="modalOpen"
    title="用户登录"
    :width="600"
    :closable="true"
    :mask-closable="true"
    :mask="true"
    :z-index="1000"
    :centered="true"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <div class="login-container">
      <!-- 标题 -->
      <div class="login-header">
        <h2>用户登录</h2>
        <p>欢迎回到智教易购平台</p>
      </div>

      <!-- 密码登录 -->
      <div class="login-section">
        <div class="login-form">
          <div class="form-item">
            <a-input
              v-model:value="username"
              placeholder="请输入用户名/手机号/邮箱"
              size="large"
              prefix="👤"
            />
          </div>
          
          <div class="form-item">
            <a-input-password
              v-model:value="password"
              placeholder="请输入密码"
              size="large"
              prefix="🔒"
            />
          </div>

          <!-- 验证码 -->
          <div class="form-item captcha-item">
            <a-input
              v-model:value="captcha"
              placeholder="请输入验证码"
              size="large"
              prefix="🔐"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img v-if="captchaImage" :src="captchaImage" alt="验证码" />
              <span v-else>点击获取验证码</span>
            </div>
          </div>

          <div class="form-options">
            <a-checkbox v-model:checked="rememberMe">记住我</a-checkbox>
            <a-button type="link" class="forgot-password" @click="showForgotPassword">忘记密码？</a-button>
          </div>

          <a-button 
            type="primary" 
            size="large" 
            block 
            class="login-btn"
            @click="handlePasswordLogin"
            :loading="passwordLoading"
          >
            登录
          </a-button>
        </div>
      </div>

      <!-- 第三方登录 -->
      <div class="third-party-section">
        <div class="divider">
          <span>第三方登录</span>
        </div>
        <div class="third-party-buttons">
          <a-button 
            v-for="(config, provider) in supportedProviders" 
            :key="provider"
            type="default" 
            size="large" 
            class="third-party-btn"
            :class="`${provider}-btn`"
            @click="handleThirdPartyLogin(provider)"
            :loading="thirdPartyLoading === provider"
            :style="{ borderColor: config.color, color: config.color }"
          >
            <component :is="getProviderIcon(provider)" />
            {{ config.name }}登录
          </a-button>
        </div>
      </div>

      <!-- 注册链接 -->
      <div class="register-section">
        <span>还没有账号？</span>
        <a-button type="link" @click="goToRegister">
          立即注册
        </a-button>
      </div>
    </div>
  
  <!-- 绑定信息页面 -->
  <BindInfoModal
    v-model:open="bindModalVisible"
    :provider="bindProvider"
    :code="bindCode"
    :role="bindRole"
    @bind-success="handleBindSuccess"
    @bind-cancel="handleBindCancel"
  />
  
  <!-- 标签选择页面 -->
  <TagSelectionModal
    v-model:open="tagSelectionVisible"
    @tag-selection-complete="handleTagSelectionComplete"
  />

  <!-- 忘记密码弹窗 -->
  <ForgotPasswordModal
    v-model:open="forgotPasswordVisible"
    @reset-success="handleForgotPasswordSuccess"
  />
  
  <!-- 第三方授权弹窗 -->
  <ThirdPartyAuthModal
    v-model:open="authModalVisible"
    :provider="authProvider"
    :provider-config="authProviderConfig"
    @auth-success="handleAuthSuccess"
    @auth-cancel="handleAuthCancel"
  />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'

// 扩展Window接口以支持临时变量
declare global {
  interface Window {
    tempAuthResolve?: (value: string) => void
    tempAuthReject?: (reason: any) => void
  }
}
import { useAuthStore } from '@/stores/authStore'
import { message, Modal } from 'ant-design-vue'
import { getCaptcha } from '@/api/user/authController'
import { loginByThird, bindAndLogin } from '@/api/user/sysOAuth2Controller'
import BindInfoModal from './BindInfoModal.vue'
import TagSelectionModal from './TagSelectionModal.vue'
import ForgotPasswordModal from './ForgotPasswordModal.vue'
import ThirdPartyAuthModal from './ThirdPartyAuthModal.vue'
import {
  WechatOutlined,
  VideoCameraOutlined,
  ShopOutlined,
  UserOutlined
} from '@ant-design/icons-vue'


interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'login-success', user: any): void
  (e: 'show-register'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => {
    emit('update:open', value)
    // 当弹窗关闭时，重置表单和刷新验证码
    if (!value) {
      resetForm()
    }
  }
})

const authStore = useAuthStore()

// 登录表单数据
const username = ref('')
const password = ref('')
const captcha = ref('')
const captchaKey = ref('')
const captchaImage = ref('')
const rememberMe = ref(false)
const passwordLoading = ref(false)
const thirdPartyLoading = ref<string | null>(null)

// 支持的第三方登录提供商
const supportedProviders = {
  wechat: { name: '微信', role: 'student', color: '#07c160', icon: 'WechatOutlined' },
  douyin: { name: '抖音', role: 'student', color: '#000000', icon: 'VideoCameraOutlined' }
} as const

// 绑定页面状态
const bindModalVisible = ref(false)
const bindProvider = ref('')
const bindCode = ref('')
const bindRole = ref('')

// 标签选择页面状态
const tagSelectionVisible = ref(false)

// 忘记密码弹窗状态
const forgotPasswordVisible = ref(false)

// 第三方授权弹窗状态
const authModalVisible = ref(false)
const authProvider = ref('')
const authProviderConfig = ref<any>(null)

// 获取验证码
const fetchCaptcha = async () => {
  try {
    const response = await getCaptcha()
    const responseData = response as any
  
    if (responseData.code === '00000') {
      captchaImage.value = responseData.data.base64Code
      captchaKey.value = responseData.data.captchaKey
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    message.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  fetchCaptcha()
}

// 重置表单
const resetForm = () => {
  username.value = ''
  password.value = ''
  captcha.value = ''
  captchaKey.value = ''
  captchaImage.value = ''
  rememberMe.value = false
  // 重新获取验证码
  fetchCaptcha()
}

// 登录方法
const handlePasswordLogin = async () => {
  if (!username.value || !password.value) {
    message.warning('请填写用户名和密码')
    return
  }
  
  passwordLoading.value = true
  try {
    // 调用真实的登录方法
    const success = await authStore.login({
      username: username.value,
      password: password.value,
      captcha: captcha.value,
      captchaKey: captchaKey.value
    })

    if (success) {
      // 登录成功，重置表单
      resetForm()
      
      // 检查是否需要选择标签
      const userInfo = authStore.userInfo
      if (userInfo && userInfo.hasTag === false) {
        // 显示标签选择页面
        tagSelectionVisible.value = true
        return
      }
      
      // 关闭弹窗并触发登录成功事件
      emit('update:open', false)
      emit('login-success', { ...authStore.userInfo, fromNormalLogin: true })
    }
  } catch (error: any) {
    console.error('登录错误:', error)
    
    // 检查是否是验证码错误，如果是则自动刷新验证码
    let isCaptchaError = false
    
    if (error.message) {
      // 检查各种可能的验证码错误信息
      const captchaErrorPatterns = [
        '验证码',
        'captcha',
        '验证码错误',
        '验证码不正确',
        '验证码已过期'
      ]
      
      isCaptchaError = captchaErrorPatterns.some(pattern => 
        error.message.toLowerCase().includes(pattern.toLowerCase())
      )
    }
    
        // 无论什么错误，都自动刷新验证码
    refreshCaptcha()
    
    // 显示错误信息
    if (isCaptchaError) {
      // 验证码错误不显示提示，静默刷新
    } else {
      message.error(error.message || '登录失败，请重试')
    }
  } finally {
    passwordLoading.value = false
  }
}

// 获取第三方平台图标
const getProviderIcon = (provider: string) => {
  switch (provider) {
    case 'wechat':
      return WechatOutlined
    case 'douyin':
      return VideoCameraOutlined
    case 'merchant_platform':
      return ShopOutlined
    case 'channel_user':
      return UserOutlined
    default:
      return UserOutlined
  }
}

// 获取角色名称
const getRoleName = (role: string) => {
  switch (role) {
    case 'student':
      return '学员'
    case 'merchant':
      return '商户'
    case 'user':
      return '用户'
    default:
      return '用户'
  }
}

// 组件挂载时获取验证码
onMounted(() => {
  fetchCaptcha()
})

// 监听弹窗打开状态，每次打开时刷新验证码
watch(() => props.open, (newOpen) => {
  if (newOpen) {
    fetchCaptcha()
  }
})

// 监听授权弹窗状态，确保状态正确重置
watch(() => authModalVisible.value, (newOpen) => {
  if (!newOpen) {
    // 当授权弹窗关闭时，重置相关状态
    authProvider.value = ''
    authProviderConfig.value = null
  }
})

// 监听加载状态变化
watch(() => thirdPartyLoading.value, (newLoading) => {
  console.log('第三方登录加载状态变化:', newLoading)
})

// 第三方登录方法
const handleThirdPartyLogin = async (provider: string) => {
  console.log('开始第三方登录:', provider)
  thirdPartyLoading.value = provider
  let mockCode = '' // 声明变量
  
  try {
    const providerConfig = supportedProviders[provider as keyof typeof supportedProviders]
    if (!providerConfig) {
      throw new Error('不支持的第三方平台')
    }
    
    // 第一步：模拟获取第三方授权码
    mockCode = await simulateGetThirdPartyCode(provider, providerConfig)
    
    // 第二步：调用后端登录接口
    const result = await loginByThird({ provider, code: mockCode })
    
    // 检查返回结果
    if ((result as any).code === '00000' && result.data) {
      const loginData = result.data as any
      
      // 检查是否需要绑定
      if (loginData.needBind) {
        // 需要绑定：首次第三方登录，显示绑定页面
        bindProvider.value = provider
        bindCode.value = mockCode
        bindRole.value = providerConfig.role
        bindModalVisible.value = true
      } else {
        // 已绑定：老用户，直接登录成功
        await handleLoginSuccess(loginData, provider)
      }
    } else {
      throw new Error((result as any).msg || '第三方登录失败')
    }
    
  } catch (error: any) {
    console.error('第三方登录错误:', error)
    const providerConfig = supportedProviders[provider as keyof typeof supportedProviders]
    
    // 处理后端抛出的具体异常
    let errorMessage = error.message || `${providerConfig?.name || '第三方'}登录失败，请重试`
    
    // 检查是否是后端返回的具体错误信息
    if (error.response?.data?.msg) {
      errorMessage = error.response.data.msg
      
      // 特殊处理未绑定异常
      if (errorMessage === 'UNBOUND_THIRD_PARTY') {
        // 显示绑定页面
        bindProvider.value = provider
        bindCode.value = mockCode
        bindRole.value = providerConfig.role
        bindModalVisible.value = true
        return // 不显示错误消息，直接显示绑定页面
      }
    }
    
    // 如果是网络错误，给出更友好的提示
    if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
      errorMessage = '网络连接失败，请检查网络后重试'
    }
    
    // 处理频率限制等特殊错误
    if (errorMessage.includes('登录次数过多') || errorMessage.includes('操作过于频繁')) {
      errorMessage = '操作过于频繁，请稍后再试'
    }
    
    message.error(errorMessage)
  } finally {
    console.log('第三方登录完成，重置加载状态')
    thirdPartyLoading.value = null
  }
}

// 模拟获取第三方授权码
const simulateGetThirdPartyCode = async (provider: string, providerConfig: any): Promise<string> => {
  return new Promise((resolve, reject) => {
    // 第一步：显示跳转提示
    Modal.confirm({
      title: `${providerConfig.name}登录`,
      content: `正在跳转到${providerConfig.name}授权页面...\n\n请在新窗口中完成授权，授权完成后将自动返回。`,
      okText: '继续',
      cancelText: '取消',
      onOk: () => {
        // 第二步：显示第三方授权弹窗
        authProvider.value = provider
        authProviderConfig.value = providerConfig
        authModalVisible.value = true
        
        // 存储resolve和reject函数，供后续使用
        window.tempAuthResolve = resolve
        window.tempAuthReject = reject
      },
      onCancel: () => {
        // 确保在用户取消时也重置加载状态
        thirdPartyLoading.value = null
        reject(new Error('用户取消登录'))
      }
    })
  })
}



// 处理绑定成功
const handleBindSuccess = async (userData: any) => {
  try {
    console.log('绑定成功，用户数据:', userData)
    
    // 获取用户输入的昵称（从绑定页面获取）
    const userNickname = localStorage.getItem('temp_nickname')
    
    // 如果后端返回的数据没有nickname，使用用户输入的昵称
    if (userData && !userData.nickname && userNickname) {
      userData.nickname = userNickname
    }
    
    console.log('处理后的用户数据:', userData)
    console.log('hasTag字段:', userData.hasTag)
    
    // 检查是否需要选择标签
    if (userData.hasTag === false) {
      console.log('需要选择标签，显示标签选择页面')
      
      // 先保存token和用户信息，确保后续API调用有认证
      const { accessToken, userId, username, nickname, roleCodes } = userData
      const userInfo = {
        id: userId,
        username: username,
        role: (roleCodes.includes('merchant') ? 'merchant' : 'student') as 'student' | 'auditor' | 'merchant' | 'admin',
        name: nickname || username,
        permissions: roleCodes,
        hasTag: false
      }
      
      // 保存到本地存储
      localStorage.setItem('token', accessToken)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      // 更新store状态
      authStore.token = accessToken
      authStore.userInfo = userInfo
      
      // 主动刷新用户信息，确保头像等完整信息被获取
      try {
        await authStore.refreshUserInfo()
        console.log('绑定后用户信息刷新成功，头像路径:', authStore.userInfo?.filePath)
      } catch (error) {
        console.error('绑定后刷新用户信息失败:', error)
        // 不影响登录流程，继续使用基本用户信息
      }
      
      console.log('已保存token和用户信息，准备显示标签选择页面')
      
      // 显示标签选择页面
      tagSelectionVisible.value = true
      return
    }
    
    console.log('不需要选择标签，直接完成登录')
    // 直接完成登录
    await handleLoginSuccess(userData, bindProvider.value)
    
    // 清除临时昵称
    localStorage.removeItem('temp_nickname')
  } catch (error) {
    console.error('绑定成功后登录失败:', error)
  }
}

// 处理绑定取消
const handleBindCancel = () => {
  bindModalVisible.value = false
  // 移除冗余的取消消息
}

// 处理标签选择完成
const handleTagSelectionComplete = async () => {
  tagSelectionVisible.value = false
  
  // 检查是否是第三方登录的新用户
  if (bindProvider.value) {
    // 第三方新用户：标签选择完成后，需要重新获取用户信息并完成登录
    console.log('第三方新用户标签选择完成，重新获取用户信息')
    
    // 获取当前存储的用户信息
    const currentUserInfo = authStore.userInfo
    if (currentUserInfo) {
      // 更新hasTag状态
      const updatedUserInfo = {
        ...currentUserInfo,
        hasTag: true
      }
      
      // 更新store和localStorage
      authStore.userInfo = updatedUserInfo
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      
      // 主动刷新用户信息，确保头像等完整信息被获取
      try {
        await authStore.refreshUserInfo()
        console.log('标签选择后用户信息刷新成功，头像路径:', authStore.userInfo?.filePath)
      } catch (error) {
        console.error('标签选择后刷新用户信息失败:', error)
        // 不影响登录流程，继续使用基本用户信息
      }
      
      // 关闭登录弹窗并触发登录成功事件
      emit('update:open', false)
      emit('login-success', { ...authStore.userInfo, fromNormalLogin: true })
    } else {
      // 如果没有用户信息，刷新页面
      console.log('没有用户信息，刷新页面')
      setTimeout(() => {
        window.location.reload()
      }, 100)
    }
  } else {
    // 普通登录用户：直接刷新页面
    console.log('普通用户标签选择完成，刷新页面')
    emit('update:open', false)
    setTimeout(() => {
      window.location.reload()
    }, 100)
  }
}

// 处理登录成功
const handleLoginSuccess = async (loginData: any, provider: string) => {
  const { accessToken, userId, username, nickname, roleCodes, hasTag } = loginData
  
  console.log('handleLoginSuccess - 原始数据:', loginData)
  console.log('handleLoginSuccess - hasTag:', hasTag)
  
  // 构建用户信息，优先使用nickname，如果没有则使用username
  const userInfo = {
    id: userId,
    username: username,
    role: (roleCodes.includes('merchant') ? 'merchant' : 'student') as 'student' | 'auditor' | 'merchant' | 'admin',
    name: nickname || username, // 优先显示nickname
    permissions: roleCodes,
    hasTag: hasTag // 确保hasTag字段被包含
  }
  
  console.log('handleLoginSuccess - 构建的用户信息:', userInfo)
  
  // 保存到本地存储
  localStorage.setItem('token', accessToken)
  localStorage.setItem('userInfo', JSON.stringify(userInfo))
  
  // 更新store状态 - 使用正确的方式
  authStore.token = accessToken
  authStore.userInfo = userInfo
  
  // 主动刷新用户信息，确保头像等完整信息被获取
  try {
    await authStore.refreshUserInfo()
    console.log('用户信息刷新成功，头像路径:', authStore.userInfo?.filePath)
  } catch (error) {
    console.error('刷新用户信息失败:', error)
    // 不影响登录流程，继续使用基本用户信息
  }
  
  // 检查是否需要选择标签
  if (hasTag === false) {
    console.log('handleLoginSuccess - 需要选择标签')
    // 显示标签选择页面
    tagSelectionVisible.value = true
    return
  }
  
  console.log('handleLoginSuccess - 不需要选择标签，直接完成登录')
  // 移除冗余的成功消息，只保留HomeView中的通知
  
  // 关闭弹窗并触发登录成功事件
  emit('update:open', false)
  emit('login-success', { ...authStore.userInfo, fromNormalLogin: true })
}

// 处理忘记密码成功
const handleForgotPasswordSuccess = () => {
  forgotPasswordVisible.value = false
  message.success('密码重置成功，请使用新密码登录！')
  // 刷新验证码
  refreshCaptcha()
}

const handleCancel = () => {
  emit('update:open', false)
}

const goToRegister = () => {
  emit('update:open', false)
  emit('show-register')
}

const showForgotPassword = () => {
  forgotPasswordVisible.value = true
}

// 处理第三方授权成功
const handleAuthSuccess = (userType: 'new' | 'existing') => {
  const provider = authProvider.value
  let code = ''
  
  if (userType === 'new') {
    // 新用户：生成随机code，模拟首次登录
    code = `mock_${provider}_new_${Date.now()}`
  } else {
    // 老用户：使用固定code，模拟已绑定用户
    code = `mock_${provider}_user_001`
  }
  
  // 关闭授权弹窗
  authModalVisible.value = false
  
  // 重置授权相关状态
  authProvider.value = ''
  authProviderConfig.value = null
  
  // 调用resolve函数
  if (window.tempAuthResolve) {
    window.tempAuthResolve(code)
    // 清理临时变量
    delete window.tempAuthResolve
    delete window.tempAuthReject
  }
  
  // 注意：这里不重置 thirdPartyLoading，因为后续的登录流程还需要使用
}

// 处理第三方授权取消
const handleAuthCancel = () => {
  // 关闭授权弹窗
  authModalVisible.value = false
  
  // 重置授权相关状态
  authProvider.value = ''
  authProviderConfig.value = null
  
  // 重置加载状态
  thirdPartyLoading.value = null
  
  // 调用reject函数
  if (window.tempAuthReject) {
    window.tempAuthReject(new Error('用户拒绝授权'))
    // 清理临时变量
    delete window.tempAuthResolve
    delete window.tempAuthReject
  }
}
</script>

<style scoped>
/* 弹窗内容样式 */
.login-container {
  padding: 24px;
}

.login-header {
  text-align: center;
  margin-bottom: 24px;
}

.login-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}



/* 登录表单 */
.login-section {
  margin-bottom: 24px;
}

.login-form {
  max-width: 400px;
  margin: 0 auto;
}

.form-item {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}

.form-item .ant-input,
.form-item .ant-input-password {
  flex: 1;
}

.captcha-item {
  gap: 12px;
}

.captcha-image {
  width: 120px;
  height: 44px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fafafa;
  transition: all 0.3s;
  overflow: hidden;
}

.captcha-image:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 4px;
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.captcha-image span {
  color: #666;
  font-size: 12px;
}

.send-code-btn {
  width: 120px;
}

.login-btn {
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  margin-top: 8px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.forgot-password {
  padding: 0;
  height: auto;
}

/* 第三方登录 */
.third-party-section {
  margin-bottom: 24px;
}

.divider {
  text-align: center;
  margin-bottom: 16px;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e8e8e8;
}

.divider span {
  background: white;
  padding: 0 16px;
  color: #999;
  font-size: 14px;
}

.third-party-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.third-party-btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
}

.wechat-btn {
  color: #07c160;
  border-color: #07c160;
}

.wechat-btn:hover {
  color: #fff;
  background: #07c160;
  border-color: #07c160;
}

.douyin-btn {
  color: #000;
  border-color: #000;
}

.douyin-btn:hover {
  color: #fff;
  background: #000;
  border-color: #000;
}



/* 注册链接 */
.register-section {
  text-align: center;
  color: #666;
}

.register-section .ant-btn {
  padding: 0;
  height: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 16px;
  }
  
  .form-item {
    flex-direction: column;
  }
  
  .captcha-image {
    width: 100%;
    height: 44px;
    min-height: 44px;
  }
  
  .third-party-buttons {
    flex-direction: column;
  }
}
</style>

